<template>
  <div class="all-btn">
    <template v-for="(item) in buttonsToDisplay">
      <!-- 按钮 -->
      <el-button v-if="!item.children" :key="item.label" :style="singleBtnStyle(item)" :type="item.type" :icon="item.icon" :size="size" @click="btnClick(item)">
        <svg-icon v-if="setSvgIcon(item.icon)" class="m-r-5" :icon-class="item.icon" />
        {{ item.label }}
      </el-button>

      <!-- 下拉菜单 -->
      <el-dropdown v-else :key="item.label" class="m-l-10" :trigger="item.trigger" :type="item.type" :size="size">
        <span class="el-dropdown-link">
          <el-button :key="item.label" :type="item.type" :icon="item.icon" :size="size">
            <svg-icon v-if="setSvgIcon(item.icon)" class="m-r-5" :icon-class="item.icon" />
            {{ item.label }}{{ item.trigger }}
          </el-button>
        </span>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="child in item.children" :key="child.lable" @click.native="btnClick(child)">
            {{ child.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </template>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  name: "MAllBtn",
  props: {
    buttonList: {
      require: true,
      type: Array,
      default: () => []
    },
    size: {
      type: String,
      default: "mini"
    },
    scope: {
      type: Object,
      default: () => {}
    }
  },
  computed: {
    ...mapGetters(["userPerm"]),
    buttonsToDisplay() {
      // 等有项目使用时把权限控制的隐藏显示添加上来
      return this.buttonList.filter(item => {
        const { hide, hasPermission } = item || {};

        // 除权限之外的按钮显示逻辑
        if (typeof hide === "undefined" || typeof hide === "boolean") {
          return !hide;
        } else if (typeof hide === "function") {
          return hide(this?.scope?.scope?.row || {});
        }

        // 是否有按钮权限
        if (hasPermission) {
          if (this.userPerm.includes(hasPermission)) {
            return true;
          }
          return false;
        }
      });
    }
  },

  methods: {
    // 单个按钮的样式
    singleBtnStyle(item) {
      const style = item?.style || {};
      return style;
    },
    //
    setSvgIcon(icon) {
      if (!icon || icon.includes("el-icon")) {
        return false;
      }
      return true;
    },
    // 点击事件
    btnClick(item) {
      if (typeof item.mthods === "function") {
        const { $index, row, search } = this?.scope?.scope || {};
        item.mthods(row, search || $index, item);
      }
    }
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
